# WeatherClock
# 一个可以显示天气情况，添加备忘录，显示专注时长等功能的智能时钟
# by 王君尧，朱敏，汪晓炜，陈格安，李睿雯小组
#该智能天气时钟会随着时间、天气的变化智能改变背景，智能改变激励的话语
#该智能天气时钟还具体帮助用户学习的功能，每日一次，每日一诗词
#注：该程序需要pygame等功能，请在安装后使用，如未安装请到python官网下载并用pip install安装
#修改城市方法：在城市代码.json中找到城市对应的代码，将WeatherClock.py 第37、183行 url 末尾城市代码替换即可。
#修改备忘录办法：在第216-218，282-284修改即可

# 检测并安装第三方库
import ModuleInstall
import pygame, requests
from sys import exit
import time
import datetime
import json
import pygame
import sys
from  pygame.locals import *
import os
import math

os.system('请先看此说明.py')

pygame.init()

# 设置窗口
size = width, height = 900, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("欢迎体验五人小组的智能天气时钟！")
WHITE = (255, 250, 250)
YELLOW= (255,255,0)



def tq():
    # 调用API，获得并整理 json 文件
    url = 'http://t.weather.sojson.com/api/weather/city/101010100'
    res = requests.get(url)
    tq_txt = res.text
    tq_json = json.loads(tq_txt)

    city = tq_json["cityInfo"]["city"]
    wendu = str(tq_json["data"]["wendu"])
    typ = tq_json["data"]["forecast"][0]["type"]
    sunrise = tq_json["data"]["forecast"][0]["sunrise"]
    sunset = tq_json["data"]["forecast"][0]["sunset"]
    fx = tq_json["data"]["forecast"][0]["fx"]
    fl = tq_json["data"]["forecast"][0]["fl"]
    air_quality = tq_json["data"]["quality"]
    shidu = str(tq_json["data"]["shidu"])
    pm25 = str(tq_json["data"]["pm25"])
    noticeee = str(tq_json["data"]["ganmao"])
    global zhuangkuang
    zhuangkuang = typ


    # 对日出日落时间取整，便于设置日出、日落时间段
    if int(sunrise[3]) >= 3:
        sunrise_h = int(sunrise[:2:]) + 1
    else:
        sunrise_h = int(sunrise[:2:])
    if int(sunset[3]) >= 3:
        sunset_h = int(sunset[:2:]) + 1
    else:
        sunset_h = int(sunset[:2:])

    return city, wendu, fx, fl, typ, sunrise_h, sunset_h, pm25, shidu, air_quality, noticeee

def print_tianqi_txt(city, wendu, fx, fl, typ, sunrise_h, sunset_h, pm25, shidu, air_quality, noticeee):
    # 显示天气文本
    font1 = pygame.font.Font('王漢宗中行書繁.ttf', 55)
    font4 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 23)
    font5 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 23)
    font6 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 23)
    font9 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 17)
    font13 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 16)
    tianqi_txt = "天气 : {}       温度 : {}°C       风向 : {}       风速 : {} ".format(typ, wendu, fx, fl)
    canshu_txt = "pm2.5 : {}       湿度 : {}      空气质量 : {}".format(pm25, shidu, air_quality)
    shijian_txt= "日出时间 :{} AM    日落时间 :{} PM".format(sunrise_h, sunset_h)
    noticese_txt="注意！："
    tq_city_txt = font1.render(city, 1, WHITE)
    tianqitxt = font4.render(tianqi_txt, 1, WHITE)
    canshu_txt = font5.render(canshu_txt, 1, WHITE)
    shijian_txt = font6.render(shijian_txt, 1, WHITE)
    notices_txt = font9.render(noticeee, 1, WHITE)
    noticese_txt = font6.render(noticese_txt, 1, WHITE)
    screen.blit(tianqitxt, (68, 140))
    screen.blit(tq_city_txt, (60, 40))
    screen.blit(canshu_txt, (68, 190))
    screen.blit(shijian_txt, (68, 240))
    screen.blit(notices_txt, (68, 320))
    screen.blit(noticese_txt, (68, 280))
    tishi_txt = "温馨提示：按w/上打开专心助手，按a/左打开未来几天天气状况;"
    newtishi_txt = "                  按d/右打开备忘录，按q/e全部打开，按s/下返回"
    newtishi_txt = font13.render(newtishi_txt, 1, YELLOW)
    tishi_txt = font13.render(tishi_txt, 1, YELLOW)
    screen.blit(tishi_txt, (38, 550))
    screen.blit(newtishi_txt, (38, 570))

def print_time_txt(year, mon, dat, h, m, s):
    # 显示时间文本
    font2 = pygame.font.Font('王漢宗中行書繁.ttf', 28)
    font3 = pygame.font.Font('王漢宗中行書繁.ttf', 90)

    font7 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 21)
    date_txt = year + "年" + mon + "月" + dat + "日"
    dattt=dat
    datt=int(dattt)
    if datt  % 7 == 1:
        jitang_txt="问渠哪得清如许？为有源头活水来。"
        xuexi_txt="每日一词：devastating--破坏性极强的"

    if datt  % 7 == 2:
        jitang_txt = "小楼一夜听春雨，深巷明朝卖杏花。"
        xuexi_txt = "每日一词：concrete--混凝土"

    if datt  % 7 == 3:
        jitang_txt = "你全力做到的最好，那就够了。"
        xuexi_txt = "每日一词：embolden--使有胆量，使勇敢"

    if datt  % 7 == 4:
        jitang_txt = "路漫漫其修远兮，吾将上下而求索————《离骚》屈原"
        xuexi_txt = "每日一词：undergo--经历，遭受"

    if datt  % 7 == 5:
        jitang_txt = "人生很多事，终究是会随着时间好起来的。"
        xuexi_txt = "每日一词：lodge--固定，卡住"

    if datt  % 7 == 6:
        jitang_txt = "人生是负重的狂奔，需要在每一个岔路口做出选择"
        xuexi_txt = "每日一词：vigil--守夜"

    else:
        jitang_txt = "前不见古人，后不见来者。念天地之悠悠，独怆然而涕下。"
        xuexi_txt = "每日一词：smash--砸烂，毁坏的"

    time_now = ("{}:{}:{}".format(h, m, s))
    jitang_txt = font7.render(jitang_txt, 1, WHITE)
    timetxt = font3.render(time_now, 1, WHITE)
    datetxt = font2.render(date_txt, 1, WHITE)
    xuexi_txt = font7.render(xuexi_txt, 1, WHITE)
    screen.blit(timetxt, (570, 480))
    screen.blit(datetxt, (620, 570))
    screen.blit(jitang_txt, (341, 40))
    screen.blit(xuexi_txt, (136, 432))

try:# 先获取一次天气信息
    tianqi = tq()

# 处理因为请求次数过多API被禁用的异常
except KeyError:
    tianqi = ('Error', '请求次数过多', '', '', '可能是因为', '', '')
    print("错误，可能是因为请求次数过多")

# 处理因为网络未连接的异常
except Exception:
    tianqi = ('Error', '未连接至互联网', '', '', '可能是因为', '', '')
    print("错误，可能是因为网络未连接")

i=1
K=1


# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        if event.type == KEYDOWN :
            if (event.key == K_LEFT or event.key == K_a):
                size = width, height = 1440, 600
                screen = pygame.display.set_mode(size)
                Nbg_n = "Nbg{}.jpg".format(stage)
                bg = pygame.image.load(Nbg_n)
                screen.blit(bg, (0, 0))  # 背景
                font10 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 30)
                font11 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 21)
                font12 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 26)
                ceshi_txt = "未来几天的天气状况如下！"
                ceshi_txt = font10.render(ceshi_txt, 1, WHITE)
                screen.blit(ceshi_txt, (1025, 40))

                url = 'http://t.weather.sojson.com/api/weather/city/101010100'
                result = requests.get(url)
                tq_txt = result.text
                tq_json = json.loads(tq_txt)
                for item in range(1,6):
                    pretyp = tq_json["data"]["forecast"][item]["type"]
                    presunrise = tq_json["data"]["forecast"][item]["sunrise"]
                    presunset = tq_json["data"]["forecast"][item]["sunset"]
                    prefx = tq_json["data"]["forecast"][item]["fx"]
                    prefl = tq_json["data"]["forecast"][item]["fl"]
                    high = tq_json["data"]["forecast"][item]["high"]
                    low = tq_json["data"]["forecast"][item]["low"]
                    ymd = tq_json["data"]["forecast"][item]["ymd"]
                    week = tq_json["data"]["forecast"][item]["week"]
                    pretianqi_txt = "{}  最{}  最{}  {} {} ".format(pretyp, high,low, prefx, prefl)
                    preriqi_txt = "日期： {}   {} ".format(ymd, week)
                    pretianqi_txt = font11.render(pretianqi_txt, 1, WHITE)
                    preriqi_txt = font12.render(preriqi_txt, 1, WHITE)
                    screen.blit(pretianqi_txt, (980, 50+item*100))
                    screen.blit(preriqi_txt, (980, 50 + item * 100-28))


            if (event.key == K_DOWN or event.key == K_s):
                size = width, height = 900, 600
                screen = pygame.display.set_mode(size)

            if (event.key == K_RIGHT or event.key == K_d):
                size = width, height = 1440, 600
                screen = pygame.display.set_mode(size)
                Nbg_n = "Nbg{}.jpg".format(stage)
                bg = pygame.image.load(Nbg_n)
                screen.blit(bg, (0, 0))  # 背景
                beiwanglu_txt = "备忘录："
                neirong1_txt="1. 下午六点开会       "
                neirong2_txt ="2. 晚上八点前交模电作业      "
                neirong3_txt = "3. 今晚完成python报告     "
                font10 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 35)
                font11 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 21)
                beiwanglu_txt = font10.render(beiwanglu_txt, 1, WHITE)
                neirong1_txt = font11.render(neirong1_txt, 1, WHITE)
                neirong2_txt = font11.render(neirong2_txt, 1, WHITE)
                neirong3_txt = font11.render(neirong3_txt, 1, WHITE)
                screen.blit(beiwanglu_txt, (1050,40))
                screen.blit(neirong1_txt, (1100, 100))
                screen.blit(neirong2_txt, (1100, 140))
                screen.blit(neirong3_txt, (1100, 180))

            if (event.key == K_UP or event.key == K_w):
                size = width, height = 1440, 600
                screen = pygame.display.set_mode(size)
                Nbg_n = "Nbg{}.jpg".format(stage)
                bg = pygame.image.load(Nbg_n)
                screen.blit(bg, (0, 0))  # 背景
                font3 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 41)
                zhuanzhu_txt = "时间专注助手:"
                zhuanzhu_txt = font3.render(zhuanzhu_txt, 1, WHITE)
                end=datetime.datetime.now()
                ssss=(end-start).seconds
                min=math.floor(ssss/60)
                sec=ssss%60
                time_use = ("当前已专心：{}分{}秒".format(min,sec))
                timeuse = font3.render(time_use, 1, WHITE)
                screen.blit(timeuse, (1030, 130))
                screen.blit(zhuanzhu_txt, (1000, 60))

            if (event.key == K_q or event.key == K_e):
                size = width, height = 1440, 780
                screen = pygame.display.set_mode(size)
                Nbg_n = "Nbg{}.jpg".format(stage)
                bg = pygame.image.load(Nbg_n)
                screen.blit(bg, (0, 0))  # 背景
                font10 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 30)
                font11 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 21)
                font12 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 26)
                ceshi_txt = "未来几天的天气状况如下！"
                ceshi_txt = font10.render(ceshi_txt, 1, WHITE)
                screen.blit(ceshi_txt, (1025, 40))

                url = 'http://t.weather.sojson.com/api/weather/city/101010100'
                result = requests.get(url)
                tq_txt = result.text
                tq_json = json.loads(tq_txt)
                for item in range(1, 6):
                    pretyp = tq_json["data"]["forecast"][item]["type"]
                    presunrise = tq_json["data"]["forecast"][item]["sunrise"]
                    presunset = tq_json["data"]["forecast"][item]["sunset"]
                    prefx = tq_json["data"]["forecast"][item]["fx"]
                    prefl = tq_json["data"]["forecast"][item]["fl"]
                    high = tq_json["data"]["forecast"][item]["high"]
                    low = tq_json["data"]["forecast"][item]["low"]
                    ymd = tq_json["data"]["forecast"][item]["ymd"]
                    week = tq_json["data"]["forecast"][item]["week"]
                    pretianqi_txt = "{}  最{}  最{}  {} {} ".format(pretyp, high, low, prefx, prefl)
                    preriqi_txt = "日期： {}   {} ".format(ymd, week)
                    pretianqi_txt = font11.render(pretianqi_txt, 1, WHITE)
                    preriqi_txt = font12.render(preriqi_txt, 1, WHITE)
                    screen.blit(pretianqi_txt, (980, 50 + item * 100))
                    screen.blit(preriqi_txt, (980, 50 + item * 100 - 28))
                beiwanglu_txt = "备忘录："
                neirong1_txt = "1. 下午六点开会       "
                neirong2_txt = "2. 晚上八点前交模电作业      "
                neirong3_txt = "3. 饭后吃药      "
                font10 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 30)
                font11 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 21)
                beiwanglu_txt = font10.render(beiwanglu_txt, 1, WHITE)
                neirong1_txt = font11.render(neirong1_txt, 1, WHITE)
                neirong2_txt = font11.render(neirong2_txt, 1, WHITE)
                neirong3_txt = font11.render(neirong3_txt, 1, WHITE)
                screen.blit(beiwanglu_txt, (60, 640))
                screen.blit(neirong1_txt, (150, 680))
                screen.blit(neirong2_txt, (150, 715))
                screen.blit(neirong3_txt, (150, 750))
                font3 = pygame.font.Font('4108_方正魏碑_GBK.ttf', 40)

                end=datetime.datetime.now()
                ssss=(end-start).seconds
                min=math.floor(ssss/60)
                sec = ssss % 60

                zhuanzhu_txt="时间专注助手："
                zhuanzhu_txt = font3.render(zhuanzhu_txt, 1, WHITE)
                time_use = ("当前已专心：{}分{}秒".format(min, sec))
                timeuse = font3.render(time_use, 1, WHITE)
                screen.blit(timeuse, (1000, 700))
                screen.blit(zhuanzhu_txt, (950, 650))


    # 获得当前日期、时间
    year = time.strftime("%Y", time.localtime(time.time()))  # 当前年数
    mon = time.strftime("%m", time.localtime(time.time()))  # 当前月数
    dat = time.strftime("%d", time.localtime(time.time()))
    m = time.strftime("%M", time.localtime(time.time()))
    h = time.strftime("%H", time.localtime(time.time()))
    s = time.strftime("%S", time.localtime(time.time()))
    inth = int(h)

    if  i==1:
        start= datetime.datetime.now()
        i=0


    # 判断早中晚（stage）
    if tianqi[5] == inth:
        stage = 1
    elif tianqi[6] == inth:
        stage = 2
    else:
        if 6 <= inth < 12:
            stage = 3
        elif 12 <= inth < 15:
            stage = 4
        elif 15 <= inth < 19:
            stage = 5
        elif 19 <= inth < 23:
            stage = 6
        else:
            stage = 7


    if zhuangkuang == ("霾" or "雾" or "大雾" ):
        bg_n = "mai.jpg"
        bg = pygame.image.load(bg_n)
    if zhuangkuang == ("小雨" or "中雨" or "大雨" or "暴雨"):
        bg_n = "yu.jpg"
        bg = pygame.image.load(bg_n)
    if zhuangkuang == ("沙尘" or "扬沙" ):
        bg_n = "sha.jpg"
        bg = pygame.image.load(bg_n)
    if zhuangkuang ==("小雪" or "中雪" or "大雪" or "暴雪"):
        bg_n = "xue.jpg"
        bg = pygame.image.load(bg_n)
    else:
        # 早中晚切换不同背景
            bg_n = "bg{}.jpg".format(stage)
            bg = pygame.image.load(bg_n)
            i=0

    # 显示
    screen.blit(bg, (0, 0))  # 背景
    print_time_txt(year, mon, dat, h, m, s)
    print_tianqi_txt(*tianqi)
    pygame.display.flip()
